﻿using Newtonsoft.Json;
using ServiceMonitor.Core;
using ServiceMonitor.Model;
using ServiceMonitor.Services.Impl;
using ServiceMonitor.Utils;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace ServiceMonitor.Services
{
    public sealed class MonitoringService
    {
        public event EventHandler<ServiceStatusChangedEventArgs> StatusChanged;
        private readonly ConcurrentDictionary<Int32, Object> monitoringServices = new ConcurrentDictionary<Int32, Object>();
        private readonly Action<String> _logger;
        private readonly string _configPath;
        private List<MonitorConfig> _configs = new List<MonitorConfig>();
        private static bool _isMonitoring;
        private int _globalInterval = 30; // 默认全局检查间隔(秒)



        public MonitoringService(Action<String> logger, string configPath)
        {
            _logger = logger;
            _configPath = configPath;
        }

        /// <summary>
        /// 获取监控状态
        /// </summary>
        /// <returns></returns>
        public static Boolean GetIsMonitoring()
        {
            return _isMonitoring;
        }

        public void StartMonitoring(int checkInterval = 30)
        {
            if (_isMonitoring) return;
            // 关闭当前系统的所有java\javaw进程    
            _globalInterval = checkInterval;
            _isMonitoring = true;
            CheckServiceStatus(null);
            _logger("监控服务已启动");
        }

        public void StopMonitoring()
        {
            if (!_isMonitoring) return;
            _isMonitoring = false;
            _logger("监控服务已停止");
        }

        public List<MonitorConfig> GetAllConfigs()
        {
            return new List<MonitorConfig>(_configs);
        }

        public void AddConfig(MonitorConfig config)
        {
            this._configs.Add(config);
            this.SaveConfigs();
            this.CheckServiceStatus(null);
        }

        public void UpdateConfig(MonitorConfig config)
        {
            var existingConfig = _configs.FirstOrDefault(c => c.Id == config.Id);
            if (existingConfig != null)
            {
                _configs.Remove(existingConfig);
                _configs.Add(config);
                SaveConfigs();
            }
        }

        public void RemoveConfig(int id)
        {
            var config = _configs.FirstOrDefault(c => c.Id == id);
            if (config != null)
            {
                _configs.Remove(config);
                SaveConfigs();
            }
        }

        public void SaveConfigs()
        {
            try
            {
                string directory = Path.GetDirectoryName(_configPath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                string json = JsonConvert.SerializeObject(_configs);
                File.WriteAllText(_configPath, json);
                _logger("配置已保存");
            }
            catch (Exception ex)
            {
                _logger("保存配置失败: " + ex.Message);
            }
        }

        public void LoadConfigs()
        {
            try
            {
                if (!File.Exists(_configPath))
                {
                    _logger($"配置文件不存在: {_configPath}");
                    return;
                }

                string json = File.ReadAllText(_configPath);
                _configs = JsonConvert.DeserializeObject<List<MonitorConfig>>(json) ?? new List<MonitorConfig>();
                _logger($"已加载 {_configs.Count} 个监控配置");
            }
            catch (Exception ex)
            {
                _logger($"加载配置失败: {ex.Message}");
            }
        }


        private void CheckServiceStatus(object state)
        {
            if (!_isMonitoring) return;

            foreach (var config in _configs)
            {
                if (!config.IsActive) continue;
                if (!monitoringServices.ContainsKey(config.Id))
                {
                    monitoringServices.TryAdd(config.Id, null);
                    try
                    {
                        switch (config.Type)
                        {
                            case MonitorType.Port:

                                AbstractStartMonitoringService Port = new TcpIPPortMonitorServiceImpl(this.StatusChanged, config, _logger);
                                ThreadPool.QueueUserWorkItem(Port.Start, state);

                                break;
                            case MonitorType.Http:
                                AbstractStartMonitoringService Http = new SpringBootMonitorServiceImpl(this.StatusChanged, config, _logger);
                                ThreadPool.QueueUserWorkItem(Http.Start, state);
                                break;
                            case MonitorType.StringBoot:
                                AbstractStartMonitoringService StringBoot = new SpringBootMonitorServiceImpl(this.StatusChanged, config, _logger);
                                ThreadPool.QueueUserWorkItem(StringBoot.Start, state);

                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        UpdateStatus(config.Id, $"检测错误: {ex.Message}");
                    }
                }

            }
        }

        public void UpdateStatus(int serviceId, string message)
        {
            // 触发事件
            StatusChanged?.Invoke(this, new ServiceStatusChangedEventArgs(serviceId, message));
        }

    }

    public class ServiceStatusChangedEventArgs : EventArgs
    {
        public int ConfigId { get; }
        public string Message { get; }

        public ServiceStatusChangedEventArgs(int configId, string message)
        {
            ConfigId = configId;
            Message = message;
        }
    }
}
